package com.seal.commons.infrastructure.redis.serialize;

import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 功能描述: <br/>
 *
 * @author yong.huang
 * @date: 2020-07-21 14:54<br/>
 * @since JDK 1.8
 */
public class StringRedisSerializer implements RedisSerializer<String> {

    private final Charset charset;

    /**
     * {@link org.springframework.data.redis.serializer.StringRedisSerializer} to use 7 bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode
     * character set.
     *
     * @see StandardCharsets#US_ASCII
     * @since 2.1
     */
    public static final StringRedisSerializer US_ASCII = new StringRedisSerializer(StandardCharsets.US_ASCII);

    /**
     * {@link org.springframework.data.redis.serializer.StringRedisSerializer} to use ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.
     *
     * @see StandardCharsets#ISO_8859_1
     * @since 2.1
     */
    public static final StringRedisSerializer ISO_8859_1 = new StringRedisSerializer(StandardCharsets.ISO_8859_1);

    /**
     * {@link org.springframework.data.redis.serializer.StringRedisSerializer} to use 8 bit UCS Transformation Format.
     *
     * @see StandardCharsets#UTF_8
     * @since 2.1
     */
    public static final StringRedisSerializer UTF_8 = new StringRedisSerializer(StandardCharsets.UTF_8);


    public StringRedisSerializer() {
        this(StandardCharsets.UTF_8);
    }


    public StringRedisSerializer(Charset charset) {

        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
    }


    @Override
    public String deserialize(@Nullable byte[] bytes) {
        return (bytes == null ? null : new String(bytes, charset));
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.data.redis.serializer.RedisSerializer#serialize(java.lang.Object)
     */
    @Override
    public byte[] serialize(@Nullable String string) {
        return (string == null ? null : string.getBytes(charset));
    }
}